package com.swx.generate.bean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;

/**
 * @author Ricky
 * @date 2020/11/24
 */
@Data
public class ApiResult<T> implements Serializable {
    private boolean success = true;
    private String code = "0";
    private String message = "";
    private T data = null;

    public ApiResult() {
    }

    private ApiResult(T data) {
        this("0", data);
    }

    private ApiResult(String code, T data) {
        this.message = "操作成功";
        this.code = code;
        this.success = "0".equals(code);
        this.data = data;
    }

    private ApiResult(String code, String message) {
        this.message = message;
        this.code = code;
        this.success = "0".equals(code);
        this.data = null;
    }

    public static <T> ApiResult<T> fail() {
        return fail("操作失败");
    }

    public static <T> ApiResult<T> fail(String message) {
        return new ApiResult<>("1001", message);
    }

    public static <T> ApiResult<T> success(T data) {
        return new ApiResult<>(data);
    }

    public static ApiResult<Boolean> success() {
        return new ApiResult<>(true);
    }

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @JSONField(serialize = false)
    public byte[] getBytes() {
        return JSON.toJSONString(this).getBytes(StandardCharsets.UTF_8);
    }
}
